package dao.impl;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import util.IOUtil;

/**
 * Class AbstractXMLDAO contains methods for loading and storing XML-files.
 * 
 * @author Daniel Dollinger
 * 
 */
public abstract class AbstractXMLDAO {
	private Logger log = LoggerFactory.getLogger(AbstractXMLDAO.class);

	protected final String rootPath;
	protected File indexFile;
	protected Document indexXMLInstance;

	public AbstractXMLDAO() {
		// rootPath = System.getProperty("user.dir") +
		// System.getProperty("file.separator") + "test_data";
		rootPath = System.getProperty("user.dir") + System.getProperty("file.separator") + "xmlotc";
	}

	/**
	 * This method is loading the XML-File by transferring it to the document
	 * type indeXMLInstance.
	 * 
	 * @throws JDOMException
	 * @throws IOException
	 */
	protected void loadXML() throws JDOMException, IOException {
		this.indexXMLInstance = new SAXBuilder().build(indexFile);
	}

	/**
	 * Storing the XML from indeXMLInstance into indexFile.
	 * 
	 * @throws IOException
	 */
	protected void storeXML() {
		XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
		indexFile = new File(rootPath);

		Writer writer = null;
		try {
			writer = new FileWriter(indexFile);
			out.output(indexXMLInstance, writer);
		} catch (IOException ioe) {
			log.error("Cannot store XML", ioe);
		} finally {
			IOUtil.safeClose(writer);
		}
	}

	/**
	 * Gets the value of 'autoincrement' in the XML-File and returns the
	 * incremented value from that.
	 * 
	 * @return
	 */
	protected int nextId() {
		Element autoIncrement = indexXMLInstance.getRootElement().getChild("autoincrement");

		int nextId = Integer.valueOf(autoIncrement.getText());
		nextId++;

		autoIncrement.setText(String.valueOf(nextId));

		storeXML();
		return nextId;
	}

}
